import uniqBy from 'lodash/uniqBy'
import find from 'lodash/find'
import { fileType } from './const/file'
import ElImageViewer from '@/components/ElImageViewer/index.vue'
import readFileSizeUnit from './mix/readFileSizeUnit/index.js'
export default {
  components: { ElImageViewer },
  mixins: [readFileSizeUnit],
  props: {
    value: {
      type: [Array, String],
      default() {
        return []
      }
    },
    fileSize: {
      type: Number,
      default: 1
    },
    ishowButton: {
      type: Boolean,
      default: true
    },
    size: {
      type: Number,
      default: 24
    }
  },
  data() {
    var token = this.$store.state.user.token
    return {
      headers: {
        token
      },
      token,
      fileList: [],
      action: this.$store.state.app.upload_url_file
    }
  },
  watch: {
    value: {
      handler(newVal, oldVal) {
        this.restructuring(newVal, oldVal)
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    restructuring(newVal, oldVal) {
      if (Array.isArray(newVal) && newVal.length > 0) {
        if (this.showList.length === 0) {
          newVal = newVal.filter((f) => {
            if (typeof this.uidsObj[f.uid] === 'boolean') {
              return this.uidsObj[f.uid]
            } else {
              return true
            }
          })
          newVal = uniqBy([...this.showList, ...newVal], 'uid')
          this.showList = newVal.map((f) => {
            if (!f.imgurl) {
              f.imgurl = f.url || f.filePath
            }
            f.isimage = this.isImage(f.imgurl)
            if (f.uid) {
              this.uidsObj[f.uid] = true
            }
            if (!f.icon) {
              var t = f.type.indexOf('image') !== -1
              f.icon = t ? '' : this.setFileIcon(f)
            }
            return f
          })
        }
        this.fileList = uniqBy([...this.fileList, ...newVal], 'uid')
      } else {
        this.fileList = []
        this.showList = []
      }
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < this.fileSize
      if (!isLt2M) {
        this.$message.error(`上传文件大小不能超过 ${this.fileSize}MB!`)
        return false
      } else {
        return true
      }
    },
    setFileIcon(v) {
      let fileExtend = ''
      var name = v.fileName || v.name
      if (name) {
        fileExtend = name.substring(name.lastIndexOf('.') + 1).toLowerCase()
      } else {
        fileExtend = 'file'
      }
      var sc = find(fileType, (o) => {
        return o.label.toLowerCase() === fileExtend
      })
      if (sc) {
        v.icon = sc.value
      }
      return v.icon
    }
  }
}
